// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef UI_BASE_IME_TEXT_INPUT_CLIENT_H_
#define UI_BASE_IME_TEXT_INPUT_CLIENT_H_

#include <stddef.h>
#include <stdint.h>

#include <string>
#include <vector>

#include "base/component_export.h"
#include "base/i18n/rtl.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "services/metrics/public/cpp/ukm_source_id.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "ui/base/ime/composition_text.h"
#include "ui/base/ime/grammar_fragment.h"
#include "ui/base/ime/input_method_delegate.h"
#include "ui/base/ime/text_input_mode.h"
#include "ui/base/ime/text_input_type.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/gfx/range/range.h"

namespace gfx {
class Rect;
}

namespace ui {

class KeyEvent;
enum class TextEditCommand;

// An interface implemented by a View that needs text input support.
// All strings related to IME operations should be UTF-16 encoded and all
// indices/ranges relative to those strings should be UTF-16 code units.
class COMPONENT_EXPORT(UI_BASE_IME) TextInputClient {
 public:
  // The reason the control was focused, used by the virtual keyboard to detect
  // pen input.
  enum FocusReason {
    // Not focused.
    FOCUS_REASON_NONE,
    // User initiated with mouse.
    FOCUS_REASON_MOUSE,
    // User initiated with touch.
    FOCUS_REASON_TOUCH,
    // User initiated with pen.
    FOCUS_REASON_PEN,
    // All other reasons (e.g. system initiated, mouse)
    FOCUS_REASON_OTHER,
  };

#if BUILDFLAG(IS_CHROMEOS_ASH)
  enum SubClass {
    kRenderWidgetHostViewAura = 0,
    kArcImeService = 1,
    kTextField = 2,
    kMaxValue = kTextField,
  };
#endif

  virtual ~TextInputClient();

  // Input method result -------------------------------------------------------

  // Sets composition text and attributes. If there is composition text already,
  // it'll be replaced by the new one. Otherwise, current selection will be
  // replaced. If there is no selection, the composition text will be inserted
  // at the insertion point.
  virtual void SetCompositionText(const ui::CompositionText& composition) = 0;

  // Converts current composition text into final content.
  // If keep_selection is true, keep the selected range unchanged
  // otherwise, set it to be after the newly committed text.
  // If text was committed, return the number of characters committed.
  // If we do not know what the number of characters committed is, return
  // UINT32_MAX.
  virtual uint32_t ConfirmCompositionText(bool keep_selection) = 0;

  // Removes current composition text.
  virtual void ClearCompositionText() = 0;

  enum class InsertTextCursorBehavior {
    // Move cursor to the position after the last character in the text.
    // e.g. for "hello", the cursor will be right after "o".
    kMoveCursorAfterText,
    // Move cursor to the position before the first character in the text.
    // e.g. for "hello", the cursor will be right before "h".
    kMoveCursorBeforeText,
  };

  // Inserts a given text at the insertion point. Current composition text or
  // selection will be removed. This method should never be called when the
  // current text input type is TEXT_INPUT_TYPE_NONE.
  virtual void InsertText(const std::u16string& text,
                          InsertTextCursorBehavior cursor_behavior) = 0;

  // Inserts a single char at the insertion point. Unlike above InsertText()
  // method, this method takes an |event| parameter indicating
  // the event that was unprocessed. This method should only be
  // called when a key press is not handled by the input method but still
  // generates a character (eg. by the keyboard driver). In another word, the
  // preceding key press event should not be a VKEY_PROCESSKEY.
  // This method will be called whenever a char is generated by the keyboard,
  // even if the current text input type is TEXT_INPUT_TYPE_NONE.
  virtual void InsertChar(const ui::KeyEvent& event) = 0;

  // Input context information -------------------------------------------------

  // Returns current text input type. It could be changed and even becomes
  // TEXT_INPUT_TYPE_NONE at runtime.
  virtual ui::TextInputType GetTextInputType() const = 0;

  // Returns current text input mode. It could be changed and even becomes
  // TEXT_INPUT_MODE_DEFAULT at runtime.
  virtual ui::TextInputMode GetTextInputMode() const = 0;

  // Returns the current text direction.
  virtual base::i18n::TextDirection GetTextDirection() const = 0;

  // Returns the current text input flags, which is a bit map of
  // WebTextInputType defined in blink. This is valid only for web input fileds;
  // it will return TEXT_INPUT_FLAG_NONE for native input fields.
  virtual int GetTextInputFlags() const = 0;

  // Returns if the client supports inline composition currently.
  virtual bool CanComposeInline() const = 0;

  // Returns current caret (insertion point) bounds in the universal screen
  // coordinates in DIP (Density Independent Pixel).
  // If there is selection, then the selection bounds will be returned.
  virtual gfx::Rect GetCaretBounds() const = 0;

  // Returns the bounds of the rectangle which encloses the selection region.
  // Bounds are in the screen coordinates. An empty value should be returned if
  // there is not any selection or this function is not implemented.
  virtual gfx::Rect GetSelectionBoundingBox() const = 0;

  // Retrieves the composition character boundary rectangle in the universal
  // screen coordinates in DIP (Density Independent Pixel).
  // The |index| is zero-based index of character position in composition text.
  // Returns false if there is no composition text or |index| is out of range.
  // The |rect| is not touched in the case of failure.
  virtual bool GetCompositionCharacterBounds(uint32_t index,
                                             gfx::Rect* rect) const = 0;

  // Returns true if there is composition text.
  virtual bool HasCompositionText() const = 0;

  // Returns how the text input client was focused.
  virtual FocusReason GetFocusReason() const = 0;

  // Document content operations ----------------------------------------------

  // Retrieves the UTF-16 code unit range containing accessible text in
  // the View. It must cover the composition and selection range.
  // Returns false if the information cannot be retrieved right now.
  virtual bool GetTextRange(gfx::Range* range) const = 0;

  // Retrieves the UTF-16 code unit range of current composition text.
  // Returns false if the information cannot be retrieved right now.
  virtual bool GetCompositionTextRange(gfx::Range* range) const = 0;

  // Retrieves the UTF-16 code unit range of current selection in the text
  // input. Returns false if the information cannot be retrieved right now.
  // Returns false if the selected text is outside of the text input (== the
  // text input is not focused)
  virtual bool GetEditableSelectionRange(gfx::Range* range) const = 0;

  // Selects the given UTF-16 code unit range. Current composition text
  // will be confirmed before selecting the range.
  // Returns false if the operation is not supported.
  virtual bool SetEditableSelectionRange(const gfx::Range& range) = 0;

  // Deletes contents in the given UTF-16 code unit range. Current
  // composition text will be confirmed before deleting the range.
  // The input caret will be moved to the place where the range gets deleted.
  // ExtendSelectionAndDelete should be used instead as far as you are deleting
  // characters around current caret. This function with the range based on
  // GetEditableSelectionRange has a race condition due to asynchronous IPCs
  // between browser and renderer. Returns false if the operation is not
  // supported.
  virtual bool DeleteRange(const gfx::Range& range) = 0;

  // Retrieves the text content in a given UTF-16 code unit range.
  // The result will be stored into |*text|.
  // Returns false if the operation is not supported or the specified range
  // is out of the text range returned by GetTextRange().
  virtual bool GetTextFromRange(const gfx::Range& range,
                                std::u16string* text) const = 0;

  // Miscellaneous ------------------------------------------------------------

  // Called whenever current keyboard layout or input method is changed,
  // especially the change of input locale and text direction.
  virtual void OnInputMethodChanged() = 0;

  // Called whenever the user requests to change the text direction and layout
  // alignment of the current text box. It's for supporting ctrl-shift on
  // Windows.
  // Returns false if the operation is not supported.
  virtual bool ChangeTextDirectionAndLayoutAlignment(
      base::i18n::TextDirection direction) = 0;

  // Deletes the current selection plus the specified number of char16 values
  // before and after the selection or caret. This function should be used
  // instead of calling DeleteRange with GetEditableSelectionRange, because
  // GetEditableSelectionRange may not be the latest value due to asynchronous
  // of IPC between browser and renderer.
  virtual void ExtendSelectionAndDelete(size_t before, size_t after) = 0;

  // Ensure the caret is not in |rect|.  |rect| is in screen coordinates in
  // DIP (Density Independent Pixel) and may extend beyond the bounds of this
  // TextInputClient.
  virtual void EnsureCaretNotInRect(const gfx::Rect& rect) = 0;

  // Returns true if |command| is currently allowed to be executed.
  virtual bool IsTextEditCommandEnabled(TextEditCommand command) const = 0;

  // Execute |command| on the next key event. This allows a TextInputClient to
  // be informed of a platform-independent edit command that has been derived
  // from the key event currently being dispatched (but not yet sent to the
  // TextInputClient). The edit command will take into account any OS-specific,
  // or user-specified, keybindings that may be set up.
  virtual void SetTextEditCommandForNextKeyEvent(TextEditCommand command) = 0;

  // Returns a UKM source for identifying the input client (e.g. for web input
  // clients, the source represents the URL of the page).
  virtual ukm::SourceId GetClientSourceForMetrics() const = 0;

  // Returns whether text entered into this text client should be used to
  // improve typing suggestions for the user. This should return false for text
  // fields that are considered 'private' (e.g. in incognito tabs).
  virtual bool ShouldDoLearning() = 0;

#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
  // Start composition over a given UTF-16 code range from existing text. This
  // should only be used for composition scenario when IME wants to start
  // composition on existing text. Returns whether the operation was successful.
  // Must not be called with an invalid range.
  virtual bool SetCompositionFromExistingText(
      const gfx::Range& range,
      const std::vector<ui::ImeTextSpan>& ui_ime_text_spans) = 0;
#endif

#if BUILDFLAG(IS_CHROMEOS_ASH)
  // Return the start and end index of the autocorrect range. If non-existent,
  // return an empty Range.
  virtual gfx::Range GetAutocorrectRange() const = 0;

  // Return the location of the autocorrect range as a gfx::Rect object.
  // If gfx::Rect is empty, then the autocorrect character bounds have not been
  // set.
  // These bounds are in screen coordinates.
  virtual gfx::Rect GetAutocorrectCharacterBounds() const = 0;

  // Sets the autocorrect range to |range|. Clients should show some visual
  // indication of the range, such as flashing or underlining. If |range| is
  // empty, then the autocorrect range is cleared.
  // Returns true if the operation was successful. If |range| is invalid, then
  // no modifications are made and this function returns false.
  virtual bool SetAutocorrectRange(const gfx::Range& range) = 0;

  // Returns the grammar fragment which contains |range|. If non-existent,
  // returns an empty Fragment.
  virtual absl::optional<GrammarFragment> GetGrammarFragment(
      const gfx::Range& range);

  // Clears all the grammar fragments in |range|, returns whether the operation
  // is successful. Should return true if the there is no fragment in the range.
  virtual bool ClearGrammarFragments(const gfx::Range& range);

  // Adds new grammar markers according to |fragments|. Clients should show
  // some visual indications such as underlining. Returns whether the operation
  // is successful.
  virtual bool AddGrammarFragments(
      const std::vector<GrammarFragment>& fragments);
#endif

#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_CHROMEOS)
  // Returns false if either the focused editable element or the EditContext
  // bounds is not available, else it returns true with the control and
  // selection bounds for the EditContext or control bounds of the active
  // editable element. This is used to report the layout bounds of the text
  // input control to TSF on Windows and to the Virtual Keyboard extension on
  // ChromeOS.
  virtual void GetActiveTextInputControlLayoutBounds(
      absl::optional<gfx::Rect>* control_bounds,
      absl::optional<gfx::Rect>* selection_bounds) = 0;
#endif

#if BUILDFLAG(IS_WIN)
  // Notifies accessibility about active composition. This API is currently
  // only defined for TSF which is available only on Windows
  // https://docs.microsoft.com/en-us/windows/desktop/api/UIAutomationCore/
  // nf-uiautomationcore-itexteditprovider-getactivecomposition
  // It notifies the composition range, composition text and whether the
  // composition has been committed or not.
  virtual void SetActiveCompositionForAccessibility(
      const gfx::Range& range,
      const std::u16string& active_composition_text,
      bool is_composition_committed) = 0;
#endif

  // Called before ui::InputMethod dispatches a not-consumed event to PostIME
  // phase. This method gives TextInputClient a chance to intercept event
  // dispatching.
  virtual void OnDispatchingKeyEventPostIME(ui::KeyEvent* event) {}
};

}  // namespace ui

#endif  // UI_BASE_IME_TEXT_INPUT_CLIENT_H_
